<template>
  <el-select :value="newValue" value-key="name" @change="handleSelectChange" multiple
             :placeholder="placeholder">
    <el-option value="">
      <el-tree :data="treeData" :props="defaultProps" :default-checked-keys="value.map(val=>val.id)" node-key="id" default-expand-all
               check-strictly show-checkbox
               @check="handleCheckChange">
      </el-tree>
    </el-option>
  </el-select>
</template>

<script>
export default {
  name: "SelectTree",
  props: {
    value: {
      type: Array,
      default: () => [],
      required: true,
    },
    placeholder: {
      type: String,
      default: '请选择'
    },
    treeData: {
      type: Array,
      default: () => [],
    },
  },
  data() {
    return {
      data: [{
        label: '一级 1',
        children: [{
          label: '二级 1-1',
          children: [{
            label: '三级 1-1-1'
          }]
        }]
      }, {
        label: '一级 2',
        children: [{
          label: '二级 2-1',
          children: [{
            label: '三级 2-1-1'
          }]
        }, {
          label: '二级 2-2',
          children: [{
            label: '三级 2-2-1'
          }]
        }]
      }, {
        label: '一级 3',
        children: [{
          label: '二级 3-1',
          children: [{
            label: '三级 3-1-1'
          }]
        }, {
          label: '二级 3-2',
          children: [{
            label: '三级 3-2-1'
          }]
        }]
      }],
      defaultProps: {
        children: 'children',
        label: 'name'
      }
    }
  },
  computed:{
    newValue(){
      return  this.value.map(item=>item.name)
    },
  },
  methods: {
    handleCheckChange(checkedNode, checkedNodes) {
      this.$emit("input", checkedNodes.checkedNodes.map(item => ({id: item.id, name: item.name})))
    },
    handleSelectChange(val) {
      const newData = {}

      this.value.forEach(item => {
        newData[item.name] = item
      })
      this.$emit("input", val.map(name => ({name, id: newData[name]})))
    }
  }
}
</script>
<style scoped>
.el-select-dropdown__item {
  height: auto;
  padding: 0;
}


</style>
